package com.kedsoft.andaily.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by Administrator on 2018/11/27.
 */
public class FileUtils {
    /**
     * 创建文件夹
     * @param path
     */
    public static void createDir(String path){
        File dir=new File(path);
        if(!dir.exists())
            dir.mkdir();
    }

    /**
     * 创建新文件
     * @param path
     * @param filename
     * @throws IOException
     */
    public static void createFile(String path,String filename) throws IOException {
        File file=new File(path+"/"+filename);
        if(!file.exists())
            file.createNewFile();
    }

    /**
     * 删除文件
     * @param path
     * @param filename
     */
    public static void delFile(String path,String filename) {
        File file=new File(path+"/"+filename);
        if(file.exists()&&file.isFile())
            file.delete();
    }

    /**
     * 删除文件夹
     * @param path
     */
    public static void delDir(String path) {
        File dir=new File(path);
        if(dir.exists()) {
            File[] tmp=dir.listFiles();
            for(int i=0;i<tmp.length;i++) {
                if(tmp[i].isDirectory()) {
                    delDir(path+"/"+tmp[i].getName());
                }
                else {
                    tmp[i].delete();
                }
            }
            dir.delete();
        }
    }

    /**
     * 读文件
     * @param path
     * @return
     * @throws IOException
     */
    public static String FileInputStreamDemo(String path) throws IOException {
        File file=new File(path);
        if(!file.exists()||file.isDirectory())
            throw new FileNotFoundException();
        FileInputStream fis=new FileInputStream(file);
        byte[] buf = new byte[1024];
        StringBuffer sb=new StringBuffer();
        while((fis.read(buf))!=-1) {
            sb.append(new String(buf));
            buf=new byte[1024];//重新生成，避免和上次读取的数据重复
        }
        return sb.toString();
    }


}
